#include "CDirectionalLight.h"
#include "CMatrix.h"

CDirectionalLight::CDirectionalLight(): m_direction(0, -1, 0), m_viewDirection(CVector3f())
{
	m_lightColor = CColor(1, 1, 1, 1);
	m_type = eDirectionalLight;
}

CDirectionalLight::CDirectionalLight(const CColor& color, const CVector3f& direction)
: m_direction(direction), m_viewDirection(CVector3f())
{
	m_lightColor = color;
	m_direction.normalize();
	m_type = eDirectionalLight;
}

CDirectionalLight::~CDirectionalLight(){}

CColor CDirectionalLight::computeColor(const CRay& /*ray*/, float /*dist*/)const
{
	return m_lightColor;
}

void CDirectionalLight::computeShadowRay(const CVector3f& point, CRay& shadowRay, float* distance)const
{
	*distance = -1;

	//to avoid intersection with itslef, move the origin along the direction
	shadowRay.setOrigin(point - m_viewDirection * 0.1f);
	shadowRay.setDirection(-m_viewDirection);
	//shadowRay.setOrigin(point - m_direction * 0.1f);
	//shadowRay.setDirection(-m_direction);
	//shadowRay.setDirection(CVector3f(m_direction.x, -m_direction.y, m_direction.z));
}

void CDirectionalLight::applyViewMatrix(const CMatrix& view)
{

	//calculate the direction vector in view coordinates
	CVector3f dirStart = CVector3f(0, 0, 0) * view;//.inverse();
	CVector3f dirEnd = m_direction * view;//.inverse();
	m_viewDirection = dirEnd - dirStart;
	m_viewDirection.normalize();
}

//set the direction
void CDirectionalLight::setDirection(const CVector3f& direction)
{
	m_direction = direction;
	m_direction.normalize();
}